// 引入vue
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)


// 路由懒加载
const routes = [
    {path:'/',redirect:'/home'
    },
    {path:'/home',component:()=> import(/* webpackChunkName: "home" */ '@/views/Home'),name:'home',meta: { requiresAuth: true },
        children:[{
            path:'search',
            component:()=>import(/* webpackChunkName: "search" */ '@/components/search'),
            meta: { requiresAuth: false }
        }]
},
    {path:'/user',component:()=> import(/* webpackChunkName: "user" */ '@/views/User'),name:'user',
    meta: { requiresAuth: true }},
    {path:'/special',component:()=> import(/* webpackChunkName: "special" */ '@/views/Special'),name:'special',
    meta: { requiresAuth: true }},
    {path:'/classify',component:()=> import(/* webpackChunkName: "classify" */ '@/views/Classify'),name:'classify',
    meta: { requiresAuth: true }},
    {path:'/car',component:()=> import(/* webpackChunkName: "car" */ '@/views/Car'),name:'car',
    meta: { requiresAuth: true }},
    {path:'/detail',component:()=> import(/* webpackChunkName: "detail" */ '@/views/Detail'),name:'detail',
    meta: { requiresAuth: false }},
    {path:'/channel',component:()=> import(/* webpackChunkName: "channel" */ '@/views/channel'),name:'channel',
    meta: { requiresAuth: false }},
    {path:'/brand',component:()=> import(/* webpackChunkName: "brand" */ '@/views/brand'),name:'brand',
    meta: { requiresAuth: false }}
]

const router = new VueRouter({
    mode:'history',
    routes
})

// 该段代码不需要记，理解即可
//在vue - router在3.1.0版本之后，push和replace方法会返回一个promise对象，如果跳转到相同的路由，
// 就报promise uncaught异常
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
    return originalPush.call(this, location).catch((err) => err);
};

// 路由卫士
router.beforeEach((to,form,next)=>{
    let token = localStorage.getItem('token')
    if(to.path=='/car'){
        if(token){
            next()
        }else{
            Vue.prototype.$toast('请先登录');
            // 定时器
            setTimeout(() => {
                next("/user");  // 强制去到"/user"所对应的路由界面
            }, 1000);
        }
    }else {
        // 如果不是去往购物车的路由，则直接通过守卫，去到to所对应的路由界面
        next()
    }
})

export default router